package com.sddnytsh.body_buildingsystem.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Send
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.navigation.NavController
import com.sddnytsh.body_buildingsystem.data.model.ChatMessage
import com.sddnytsh.body_buildingsystem.data.model.Contact
import com.sddnytsh.body_buildingsystem.data.model.MessageType
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

@Composable
fun MessageBubble(
    message: ChatMessage,
    isFromCurrentUser: Boolean,
    onLongPress: () -> Unit
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = if (isFromCurrentUser) Arrangement.End else Arrangement.Start
    ) {
        Card(
            modifier = Modifier
                .widthIn(max = 280.dp)
                .pointerInput(Unit) {
                    detectTapGestures(
                        onLongPress = { onLongPress() }
                    )
                },
            shape = RoundedCornerShape(
                topStart = 16.dp,
                topEnd = 16.dp,
                bottomStart = if (isFromCurrentUser) 16.dp else 4.dp,
                bottomEnd = if (isFromCurrentUser) 4.dp else 16.dp
            ),
            colors = CardDefaults.cardColors(
                containerColor = if (isFromCurrentUser) Color(0xFF1976D2) else Color.White
            ),
            elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
        ) {
            Column(
                modifier = Modifier.padding(12.dp)
            ) {
                Text(
                    text = message.content,
                    style = MaterialTheme.typography.bodyMedium.copy(
                        color = if (isFromCurrentUser) Color.White else Color(0xFF212529)
                    )
                )
                
                Spacer(modifier = Modifier.height(4.dp))
                
                Text(
                    text = SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date(message.timestamp)),
                    style = MaterialTheme.typography.bodySmall.copy(
                        color = if (isFromCurrentUser) Color.White.copy(alpha = 0.7f) else Color.Gray
                    )
                )
            }
        }
    }
}

@Composable
fun ChatScreen(navController: NavController, contactId: Long) {
    var messageText by remember { mutableStateOf("") }
    var contact by remember { mutableStateOf<Contact?>(null) }
    var messages by remember { mutableStateOf<List<ChatMessage>>(emptyList()) }
    var showMessageOptions by remember { mutableStateOf(false) }
    var selectedMessage by remember { mutableStateOf<ChatMessage?>(null) }

    // 模拟联系人信息（关注的人）
    val contacts = remember {
        listOf(
            Contact(1, "张三", "", "你好，最近怎么样？", "10:30", 2),
            Contact(2, "李四", "", "明天一起健身吧", "09:15", 0),
            Contact(3, "王五", "", "好的，没问题", "昨天", 1),
            Contact(4, "赵六", "", "今天天气真不错", "昨天", 0),
            Contact(5, "孙七", "", "晚上一起跑步", "周二", 3)
        )
    }

    // 模拟聊天消息
    val initialMessages = remember {
        listOf(
            ChatMessage(1, contactId, 1, "你好！", System.currentTimeMillis() - 3600000, true),
            ChatMessage(
                2,
                1,
                contactId,
                "你好，最近怎么样？",
                System.currentTimeMillis() - 3500000,
                true
            ),
            ChatMessage(
                3,
                contactId,
                1,
                "还不错，你呢？",
                System.currentTimeMillis() - 3400000,
                true
            ),
            ChatMessage(
                4,
                1,
                contactId,
                "我也很好，明天一起健身吧",
                System.currentTimeMillis() - 3300000,
                true
            ),
            ChatMessage(5, contactId, 1, "好的，没问题！", System.currentTimeMillis() - 3200000, true)
        )
    }

    val listState = rememberLazyListState()

    // 查找联系人信息
    LaunchedEffect(contactId) {
        contact = contacts.find { it.id == contactId }
        messages = initialMessages
    }

    // 自动滚动到底部
    LaunchedEffect(messages.size) {
        if (messages.isNotEmpty()) {
            listState.animateScrollToItem(messages.size - 1)
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0xFFF8F9FA))
    ) {
        // 顶部标题栏
        Card(
            modifier = Modifier.fillMaxWidth(),
            colors = CardDefaults.cardColors(containerColor = Color.White),
            elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
            shape = RoundedCornerShape(bottomStart = 16.dp, bottomEnd = 16.dp)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                IconButton(
                    onClick = { navController.popBackStack() }
                ) {
                    Icon(
                        imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                        contentDescription = "返回",
                        tint = Color(0xFF1976D2)
                    )
                }

                Spacer(modifier = Modifier.width(8.dp))

                // 联系人头像
                Box(
                    modifier = Modifier
                        .size(44.dp)
                        .clip(CircleShape)
                        .background(Color(0xFFE3F2FD)),
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        imageVector = Icons.Default.Person,
                        contentDescription = "头像",
                        tint = Color(0xFF1976D2),
                        modifier = Modifier.size(22.dp)
                    )
                }

                Spacer(modifier = Modifier.width(12.dp))

                Column {
                    Text(
                        text = contact?.name ?: "未知联系人",
                        style = MaterialTheme.typography.titleMedium.copy(
                            fontWeight = FontWeight.SemiBold,
                            color = Color(0xFF212529)
                        )
                    )
                    Text(
                        text = "在线",
                        style = MaterialTheme.typography.bodySmall.copy(
                            color = Color(0xFF28A745)
                        )
                    )
                }
            }
        }

        // 消息列表
        LazyColumn(
            modifier = Modifier
                .weight(1f)
                .fillMaxWidth()
                .background(Color(0xFFF8F9FA)),
            state = listState,
            contentPadding = androidx.compose.foundation.layout.PaddingValues(16.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            items(messages) { message ->
                MessageBubble(
                    message = message,
                    isFromCurrentUser = message.senderId == contactId,
                    onLongPress = {
                        selectedMessage = message
                        showMessageOptions = true
                    }
                )
            }
        }

        // 输入框
        Card(
            modifier = Modifier.fillMaxWidth(),
            colors = CardDefaults.cardColors(containerColor = Color.White),
            elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
            shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                OutlinedTextField(
                    value = messageText,
                    onValueChange = { messageText = it },
                    placeholder = { Text("输入消息...", color = Color.Gray) },
                    modifier = Modifier.weight(1f),
                    colors = TextFieldDefaults.colors(
                        focusedContainerColor = Color.Transparent,
                        unfocusedContainerColor = Color.Transparent,
                        focusedIndicatorColor = Color(0xFF1976D2),
                        unfocusedIndicatorColor = Color.Gray
                    ),
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
                    shape = RoundedCornerShape(20.dp)
                )

                Spacer(modifier = Modifier.width(12.dp))

                Button(
                    onClick = {
                        if (messageText.isNotBlank()) {
                            // 发送消息
                            val newMessage = ChatMessage(
                                id = messages.size + 1L,
                                senderId = contactId,
                                receiverId = contact?.id ?: 1L,
                                content = messageText,
                                timestamp = System.currentTimeMillis(),
                                isRead = false
                            )
                            messages = messages + newMessage
                            messageText = ""
                        }
                    },
                    modifier = Modifier.size(48.dp),
                    shape = CircleShape,
                    colors = androidx.compose.material3.ButtonDefaults.buttonColors(
                        containerColor = Color(0xFF1976D2)
                    ),
                    enabled = messageText.isNotBlank()
                ) {
                    Icon(
                        imageVector = Icons.Default.Send,
                        contentDescription = "发送",
                        tint = Color.White,
                        modifier = Modifier.size(20.dp)
                    )
                }
            }
        }

        // 长按消息操作对话框
        if (showMessageOptions && selectedMessage != null) {
            AlertDialog(
                onDismissRequest = {
                    showMessageOptions = false
                    selectedMessage = null
                },
                title = { Text("消息操作") },
                text = { Text("请选择要执行的操作") },
                confirmButton = {
                    TextButton(
                        onClick = {
                            // 撤回消息
                            messages = messages.filter { it.id != selectedMessage?.id }
                            showMessageOptions = false
                            selectedMessage = null
                        }
                    ) {
                        Text("撤回")
                    }
                },
                dismissButton = {
                    TextButton(
                        onClick = {
                            // 删除消息
                            messages = messages.filter { it.id != selectedMessage?.id }
                            showMessageOptions = false
                            selectedMessage = null
                        }
                    ) {
                        Text("删除")
                    }
                }
            )
        }
    }
}
